package com.lt.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lt.reggie.common.R;
import com.lt.reggie.dto.DishDto;
import com.lt.reggie.entity.Category;
import com.lt.reggie.entity.Dish;
import com.lt.reggie.entity.DishFlavor;
import com.lt.reggie.entity.SetmealDish;
import com.lt.reggie.service.CategoryService;
import com.lt.reggie.service.DishFlavorService;
import com.lt.reggie.service.DishService;
import com.lt.reggie.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清理对应修改菜品的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
//        dishService.save()
        return R.success("添加菜品成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page = {}, pageSize = {}, name = {}", page, pageSize, name);
        //分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo, queryWrapper);
        //对象拷贝                                                    //数据不进行拷贝
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");

        List<Dish> dishList = pageInfo.getRecords();
        //将pageInfo中的数据传递给dishDtoPage，并加上分类名
        List<DishDto> list = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //将list中的对象属性拷贝给dishDto对象
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId(); //分类id
            Category category = categoryService.getById(categoryId); //根据id查分类对象
            //判断根据id查数据返回的值是否为空
            if (category != null) {
                String categoryName = category.getName();//分类名
                dishDto.setCategoryName(categoryName);//设置分类名
            }
            return dishDto;
            //重新封装到集合中
        }).collect(Collectors.toList());

        //将已经赋好值的集合添加到dishDtoPage中
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查菜品和口味
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);

//        //清理所有菜品缓存
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);
        //清理对应修改菜品的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改成功");
    }

    /**
     * 根据id删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<String> ids) {
        log.info(ids.toString());
        //清理对应删除菜品的缓存
        for (String id : ids) {
            Dish dish = dishService.getById(id);
            Long categoryId = dish.getCategoryId();
            String key = "dish_" + categoryId + "_1";
            redisTemplate.delete(key);
        }
        dishService.deleteWithFlavor(ids);
        return R.success("删除成功");
//        return null;
    }

    /**
     * 停售和批量停售
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable int status, @RequestParam List<String> ids) {
        log.info("ids = {},status = {}", ids, status);
        //清理对应停产菜品的缓存
        for (String id : ids) {
            Dish dish = dishService.getById(id);
            Long categoryId = dish.getCategoryId();
            String key = "dish_" + categoryId + "_1";
            redisTemplate.delete(key);
        }
        dishService.updateOrListWithFlavor(status, ids);
        return R.success("修改成功");
    }



    /*  *//**
     * 根据菜品分类查出所包含的菜品数据
     * @param dish
     * @return
     *//*
    @GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        log.info(dish.toString());
        //构建查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加状态为1（起售）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(dish.getName() != null,Dish::getName,dish.getName());
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //执行条件查询
        List<Dish> dishList = dishService.list(queryWrapper);
        return R.success(dishList);
    }*/

    /**
     * 根据菜品分类查出所包含的菜品数据
     *
     * @param dish
     * @return
     */

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        log.info(dish.toString());

        List<DishDto> dishDtoList = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //从redis缓存中获取数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        log.info("key : {}", key);
        if (dishDtoList != null) {
            //如果存在则直接返回数据
            return R.success(dishDtoList);
        }
        //如果不存在则从数据库查询数据
        //构建查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加状态为1（起售）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.eq(dish.getName() != null, Dish::getName, dish.getName());
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //执行条件查询
        List<Dish> dishList = dishService.list(queryWrapper);
        //将dishList中的数据传递给dishDtoList
        dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //将list中的对象属性拷贝给dishDto对象
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId(); //分类id
            Category category = categoryService.getById(categoryId); //根据id查分类对象
            //判断根据id查数据返回的值是否为空
            if (category != null) {
                String categoryName = category.getName();//分类名
                dishDto.setCategoryName(categoryName);//设置分类名
            }
            //查询当前菜品口味信息
            //当前菜品id
            Long dishId = item.getId();
            //条件构造器
            LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            flavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //执行条件查询
            List<DishFlavor> dishFlavorList = dishFlavorService.list(flavorLambdaQueryWrapper);
            //将查询菜品口味结果添加进dishDto对象中
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
            //重新封装到集合中
        }).collect(Collectors.toList());

        //将查询到的数据缓存到redis中
        redisTemplate.opsForValue().set(key, dishDtoList ,60 , TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }
}
